<?php
session_start();
require_once('../config.php');
require('../smarty/smarty_config.php');
require('../model/catalog/catalog.php');
require('../model/post/post.php');



$id = $_GET['id'];
$f = $_GET['f'];
if (empty($_SESSION['USER_ID'])) {
	header('location:index.php');
	exit;	
}
if(empty($f)) {
	$f = 'list';
}



$smarty -> display('./admin/header.tpl');
$smarty ->display('./admin/admin-left.tpl');

$post = new Post();
switch ($f) {
	// show the detail of the post with given indentity id
	case 'show':
		if (empty($id)) {
			header('location:index.php');
			exit;
		}
		if ($post_info = $post -> get_post()){
			$smarty -> assign('post',$post_info);
		}
		$smarty ->display('./admin/post.tpl');
		break;
		
	case 'list':
	
		$posts_list = $post -> get_post_all_valid();
		$smarty -> assign('posts_list',$posts_list);
		
		$smarty -> display('./admin/posts-list.tpl');
		break;
	// add a post
	case 'add':		
		if (empty($_POST['OP']) || $_POST['OP'] ='' ) {			
			$catalog = new Catalog();
			$catalogs_list = $catalog -> get_post_all_valid();
			
			$smarty -> assign('catalogs_list',$catalogs_list);
			$smarty	-> assign('f','add');
			$smarty -> assign('id',$id);			
			$smarty -> display('./admin/add-post.tpl');
			$smarty -> display('./admin/foot.tpl');
		} else if($_POST['OP'] = 'submit') {
			if ($post -> add_new_post()) {				
				$smarty -> display('./admin/add-post-ok.tpl');
			}
		}
		break;
	// update a post
	case 'modify':			
		if (empty($id)) {
			header('location:index.php');
			exit;
		}
		if (empty($_POST['OP'])){
			if ($post_info = $post -> get_post()){
				$catalog = new Catalog();
				$catalogs_list = $catalog -> get_post_all_valid();			
				$smarty -> assign('catalogs_list',$catalogs_list);
				$smarty	-> assign('f','modify');
				$smarty -> assign('id',$id);
				$smarty -> assign('post_info',$post_info);
				$smarty -> display('./admin/add-post.tpl');
			}
		}else if ($_POST['OP'] ='submit') {
//			$sql = "update post set date_modified = now(),title= '$_POST[title]',content = '$_POST[content]',user_name='$_SESSION[USER_NAME]' where id = $id";
//			echo $sql;
//			$result = $db -> run_sql_query($sql);
			if ($post -> update_post()) {
				$smarty -> display('./admin/add-post-ok.tpl');
			}
		}
		break;
	// delete a post ,actully ,you know ,we always dont delete it ,just modify it.	
	case 'delete':
		if (empty($id)) {
			header('location:index.php');
			exit;
		}
//		$sql = "update post set valid =0 ,date_modified = now() where id = $id";			
//		$result = $db -> run_sql_query($sql);
		if ($post -> delete_post()) {
			$smarty -> display('./admin/add-post-ok.tpl');
		}		
		break;
		
	case 'dirtyposts':
		$posts_list = $post -> get_posts_all_dirty();
		$smarty -> assign('posts_list',$posts_list);
		
		$smarty -> display('./admin/posts-list.tpl');
		break;	
	default:
		$smarty ->display('./admin/foot.tpl');
}



